package com.zto.mybatis.interceptor;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Properties;

/**
 * Created by xingyuchao on 2017-07-02.
 */
@Intercepts({@Signature(
        type = Executor.class, //只能是: StatementHandler | ParameterHandler | ResultSetHandler | Executor 类或者子类
        method = "query",   // 表示：拦截Executor的query方法
        args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}    // query 有很多的重载方法，需要通过方法签名来指定具体拦截的是那个方法
)})
public class SqlInterceptor implements Interceptor {

    private static Logger logger = LoggerFactory.getLogger(SqlInterceptor.class);

    public Object intercept(Invocation invocation) throws Throwable {

        MappedStatement statement = (MappedStatement) invocation.getArgs()[0]; //获取的是args参数MappedStatement，

        BoundSql boundSql = statement.getBoundSql(invocation.getArgs()[1]);


        logger.info("sql: {}" , boundSql.getSql());//打印sql语句
        logger.info("params: {}",boundSql.getParameterObject());//打印参数.
        //通过invocation.proceed()方法完成调用链的推进
        return invocation.proceed();
    }

    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    //用于设置额外的参数，参数配置在拦截器的Properties节点里。
    public void setProperties(Properties properties) {
        Object name = properties.get("name");
        logger.info("{}",name);
    }
}
